/*
 * Copyrignt (c) xuzeshui.com. All Rights Reserved.
 * Author: Xiaobao Zeng<zengxiaobao@skyworth.com>
 * Created Time: 2017-05-17 17:52:13
 * Last Modified: 2017-07-10 14:34:55
 * File Name: statis.go
 * Description:
 */

package statis

import (
	"errors"
	"fmt"
	"strconv"
	"strings"
	"time"

	"qkstatis/db"

	log "github.com/cihub/seelog"
)

var weekday map[string]string

//公共方法
//判断web传递时间参数是否正确
func (p *StatisService) IsValidTimeRange(ltype int, timeRange string) (bool, string, string) {
	tr := strings.Replace(timeRange, " ", "", -1)
	trArray := strings.Split(tr, "~")
	if ltype != 3 && len(trArray) != 2 && trArray[0] > trArray[1] {
		return false, "", ""
	}
	switch ltype {
	case 1:
		if len(trArray[0]) != 6 || len(trArray[1]) != 6 {
			return false, "", ""
		}
	case 2:
		year, week := time.Now().ISOWeek()
		if len(trArray[0]) != 6 || len(trArray[1]) != 6 {
			return false, "", ""
		} else if trArray[0] == "000000" && trArray[1] == "000000" {
			trArray[0] = fmt.Sprintf("%d%02d", year, week-2)
			trArray[1] = fmt.Sprintf("%d%02d", year, week+1)
		} else {
			end, _ := strconv.Atoi(trArray[1])
			trArray[1] = fmt.Sprintf("%d", end+1)
		}
	case 3:
		if len(trArray) == 2 {
			return true, trArray[0], trArray[1]
		}
		now := time.Now().Format("0601")
		return true, "1612", now
	}
	return true, trArray[0], trArray[1]
}

//获取时间
func (p *StatisService) GetTimes(ltype int, start string) (error, []string) {
	sql := "select date_flag from "
	switch ltype {
	case 2:
		sql = fmt.Sprintf("%s statis_all_profit_week where date_flag >= %s order by date_flag desc", sql, start)
	case 3:
		sql = fmt.Sprintf("%s statis_all_profit_month where date_flag >= %s order by date_flag desc", sql, start)
	default:
	}
	mysqlHelper := db.GetMySQLHelper()
	if results, err := mysqlHelper.Query(sql); err == nil {
		if 0 == len(results) {
			return errors.New("查询结果为空,换一个时间进行查询"), nil
		}

		resp := make([]string, 0, len(results))
		for _, dt := range results {
			dateFlag := mysqlHelper.GetColString(dt, "date_flag")
			resp = append(resp, dateFlag)
		}
		return nil, resp
	} else {
		log.Errorf("GetTimes mysql err; err:%s", err.Error())
	}
	return errors.New("服务器内部错误"), nil
}

//将日期转化为星期字符串
func (p *StatisService) date2week(date string) string {
	loc, _ := time.LoadLocation("Local")
	if t, err := time.ParseInLocation("060102", date, loc); err == nil {
		weekstr := t.Weekday().String()
		return weekday[weekstr]
	} else {
		log.Warnf("date2week fail; date:%s, err:%s", date, err.Error())
	}
	return "x"
}
